package net.cyl.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.mysql.cj.xdevapi.Table;
import lombok.extern.slf4j.Slf4j;
import net.cyl.config.RabbitMQConfig;
import net.cyl.controller.request.AccountLoginRequest;
import net.cyl.controller.request.AccountRegisterRequest;
import net.cyl.emums.AuthTypeEnum;
import net.cyl.emums.BizCodeEnum;
import net.cyl.emums.EventMessageType;
import net.cyl.emums.SendCodeEnum;
import net.cyl.manager.AccountManager;
import net.cyl.model.AccountDO;
import net.cyl.mapper.AccountMapper;
import net.cyl.model.EventMessage;
import net.cyl.model.LoginUser;
import net.cyl.service.AccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.cyl.util.CommonUtil;
import net.cyl.util.IDUtil;
import net.cyl.util.JWTUtil;
import net.cyl.util.JsonData;
import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 曹玉林
 * @since 2025-05-09
 */
@Service
@Slf4j
public class AccountServiceImpl extends ServiceImpl<AccountMapper, AccountDO> implements AccountService {
     @Autowired
     private NotifyServiceImpl notifyService;
     @Autowired
     private AccountManager accountManager;
     @Autowired
     private RabbitTemplate rabbitmqTemplate;
     @Autowired
     private RabbitMQConfig rabbitMQConfig;
     private static final Long  FREE_TRAFFIC_PRODUCT_ID = 1L;
    /**
     * 手机验证码注册
     * 密码加密存储
     * 账号唯一性校验
     * 插入数据库
     * 新用户发放福利
     * @param registerRequest
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public JsonData register(AccountRegisterRequest registerRequest) {
        //校验手机验证码
        boolean checkCode = false;
        if(StringUtils.isNotBlank(registerRequest.getPhone())){
            checkCode = notifyService.checkCode(SendCodeEnum.USER_REGISTER,registerRequest.getPhone(),registerRequest.getCode());

        }
        if(!checkCode){
            return JsonData.buildResult(BizCodeEnum.CODE_ERROR);
        }
        //创建账号对象
        AccountDO accountDO = new AccountDO();
        BeanUtils.copyProperties(registerRequest,accountDO);
        accountDO.setAuth(AuthTypeEnum.DEFAULT.name());

        //密码加密
        accountDO.setSecret("$1$"+ CommonUtil.getStringNumRandom(8));
        String cryptPassword = Md5Crypt.md5Crypt(registerRequest.getPwd().getBytes(),accountDO.getSecret());
        accountDO.setPwd(cryptPassword);
        //todo
        //生成账号编号
        accountDO.setAccountNo((Long) IDUtil.generateSnowflakeKey());
        //插入数据库
        int row= accountManager.insert(accountDO);
        log.info("注册成功，row={}",row);
        //发放福利
        userRegisterWelfare(accountDO);
        return JsonData.buildSuccess();
    }

    @Override
    public JsonData login(AccountLoginRequest loginRequest) {
        //根据手机号查询账号
        List<AccountDO> accountDOList = accountManager.findbyPhone(loginRequest.getPhone());
        if(accountDOList!=null&&accountDOList.size()==1){
            AccountDO accountDO = accountDOList.get(0);
            //密码加密
            String cryptPassword = Md5Crypt.md5Crypt(loginRequest.getPassword().getBytes(),accountDO.getSecret());
            //校验密码
            if(cryptPassword.equalsIgnoreCase(accountDO.getPwd())){
                //生成登录用户对象
                LoginUser loginUser = LoginUser.builder().build();
                BeanUtils.copyProperties(accountDO,loginUser);

                return JsonData.buildSuccess(JWTUtil.generateToken(loginUser));
            }
            else{
                return JsonData.buildResult(BizCodeEnum.ACCOUNT_PWD_ERROR);
            }
        }
        else{
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_UNREGISTER);
        }

    }


    private void userRegisterWelfare(AccountDO accountDO){
        EventMessage  eventMessage = EventMessage.builder()
                .messageId(IDUtil.generateSnowflakeKey().toString())
                .accountNo(accountDO.getAccountNo())
                .eventType(EventMessageType.TRAFFIC_FREE_INIT.name())
                .bizId(String.valueOf(FREE_TRAFFIC_PRODUCT_ID))
                .build();
        rabbitmqTemplate.convertAndSend(rabbitMQConfig.getTrafficEventExchange(),rabbitMQConfig.getTrafficFreeInitRoutingKey(), eventMessage);
    }
}
